package com.aweqy.subjectredis.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aweqy.subjectredis.common.BaseResponse;
import com.aweqy.subjectredis.common.ResultUtils;
import com.aweqy.subjectredis.config.RedisKeyService;
import com.aweqy.subjectredis.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;


@Controller
@RequestMapping("/subject")
public class BasicController {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate; // 专门处理String类型的RedisTemplate

    @Autowired
    private RedisKeyService redisKeyService;

    private List<Integer> arr = new ArrayList<>();
    private int p = 0;

    /**
     * 获取题目
     *
     * @param key key
     * @return BaseResponse<String>
     */
    @GetMapping("/get")
    @ResponseBody
    public BaseResponse<String> getOfKey(@RequestParam String key) {
        String result = stringRedisTemplate.opsForValue().get(key);
        return ResultUtils.success(result);
    }

    /**
     * 上传题目
     *
     * @param category 类别
     * @param content  题目
     * @param answer   答案
     * @return BaseResponse<String>
     */
    @PostMapping("/post")
    @ResponseBody
    public BaseResponse<?> setOfKey(@RequestParam String category, @RequestParam String content, @RequestParam String answer) {
        // 生成自增key（subject:category:ids）
        // category（select:1/blanks:2/saq:3）
        String prefix = "subject:" + category;
        Long id = redisTemplate.opsForValue().increment(prefix + ":counter");
        String key = prefix + ":" + id;
        // 获取分类名称
        String categoryName = stringRedisTemplate.opsForValue().get("subject:category:" + category);
        // 创建JSONObject
        JSONObject json = JSONUtil.createObj()
                .put("category", categoryName)
                .put("content", content)
                .put("answer", answer);
        // 存入 Redis 数据库
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(json));
        return ResultUtils.success(JSONUtil.toJsonStr(json));
    }

    /**
     * 新增类别
     *
     * @param title 类别名称
     * @return
     */
    @PostMapping("/addCategory")
    @ResponseBody
    public BaseResponse<?> addOfCategory(@RequestParam String title) {
        JSONObject json = null;
        try {
            // 生成key（subject:category:ids）
            String prefix = "subject:category";
            Long id = redisTemplate.opsForValue().increment(prefix + ":counter");
            String key = prefix + ":" + id;
            // 存入 Redis 数据库
            stringRedisTemplate.opsForValue().set(key, title);
        } catch (BusinessException e) {
            return ResultUtils.error(e.getCode(), e.getMessage());
        }
        return ResultUtils.success(title);
    }

    /**
     * 获取所有分类
     *
     * @return
     */
    @GetMapping("/get/AllCategory")
    @ResponseBody
    public BaseResponse<?> getAllCategory() {
        // 获取所有类名
        String key = "subject:category:*";
        Set<String> subjectCategoryKeys = redisKeyService.getSubjectCategoryKeys(key);
        // 获取相应key的value
        JSONObject jsonObj = JSONUtil.createObj();
        for (String subjectCategoryKey : subjectCategoryKeys) {
            String vlaue = stringRedisTemplate.opsForValue().get(subjectCategoryKey);
            // 转化为json格式
            jsonObj.put(subjectCategoryKey, vlaue);
        }
        return ResultUtils.success(jsonObj);
    }

    /**
     * 获取类下所有value
     *
     * @param category 类id
     * @return
     */
    @GetMapping("/get/AllValue")
    @ResponseBody
    public BaseResponse<?> getAllValue(@RequestParam String category) {
        // 获取所有类名
        String key = "subject:" + category + ":*";
        Set<String> subjectValueKeys = redisKeyService.getSubjectCategoryKeys(key);
        // 获取相应key的value
        JSONObject jsonObj = JSONUtil.createObj();
        for (String subjectCategoryKey : subjectValueKeys) {
            String vlaue = stringRedisTemplate.opsForValue().get(subjectCategoryKey);
            // 转化为json格式
            jsonObj.put(subjectCategoryKey, vlaue);
        }
        return ResultUtils.success(jsonObj);
    }

    /**
     * 随机获取类下value
     *
     * @param category
     * @return
     */
    @GetMapping("/get/value")
    @ResponseBody
    public BaseResponse<?> getValue(@RequestParam String category) {
        // 获取所有类名
        String key = "subject:" + category + ":*";
        Set<String> subjectValueKeys = redisKeyService.getSubjectCategoryKeysExcludingCounters(key);
        String[] ofKey = subjectValueKeys.toArray(new String[subjectValueKeys.size()]);
        // 生成一个数组，随机排序
        if (p >= ofKey.length || p == 0) {
            arr = new ArrayList<>(ofKey.length);
            for (int i = 0; i < ofKey.length; i++) {
                arr.add(i);
            }
            Collections.shuffle(arr);
            p = 0;
        }
        // 随机一个题目
//        System.out.println(p + ":" + ofKey[arr.get(p++)]);
        // 获取相应key的value
        String vlaue = stringRedisTemplate.opsForValue().get(ofKey[arr.get(p++)]);
        return ResultUtils.success(vlaue);
    }

}
